var loginPath = "/front/login";
var registerPath = "/front/register";
var tokenName = "token";
var rankListPageSize = 10; //rankList的每页大小
var statusPageSize = 10; //status的每页大小
var contestListPageSize = 10; //contestList的每页大小
var probleListPageSize = 10; //probleList的每页大小

var HttpStatus = new Object();
HttpStatus.UNAUTHORIZED = 401;
HttpStatus.SUCCESS = 200;


function errorHandle(obj) {
    //unathorized
    var errno = obj.errno;
    if (errno == HttpStatus.UNAUTHORIZED) {
        sessionStorage.setItem("preURL", window.location.href);
        localStorage.removeItem(tokenName);
        localStorage.removeItem("name");
        window.location.pathname = loginPath;
    }
    else {
        if (obj.warnObjId != null) {
            document.getElementById(obj.warnObjId).textContent = obj.message;
        }
    }
}

function getUrlVar(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0; i<vars.length; ++i) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return null;
}
function checkName(arg) {
    var pat = /^[0-9a-zA-Z_]+$/;
    var ret = pat.test(arg);
    return ret;
}
function isBlank(arg) {
    if (arg == null || arg == "") {
        return true;
    }
    var len = arg.length;
    for (var i=0; i<len; ++i) {
        if (arg[i] != ' ') {
            return false;
        }
    }
    return true;
}
//登陆前记住前一页地址
function preLogin() {
    var prePath = window.location.pathname;
    if (prePath != loginPath && prePath != registerPath) {
        sessionStorage.setItem("preURL", window.location.href);
    }
    window.location.pathname = loginPath;
}
function preRegister() {
    var prePath = window.location.pathname;
    window.location.pathname = registerPath;
}
function showInfo() {
    window.location = "user?userName=" + localStorage.getItem("name").toString();
}
function logout() {
    localStorage.clear();
    sessionStorage.clear();
    window.location = "index";
}
function userInfo(obj, name) {
    getObj(obj).innerHTML = 'Hi! <span class="name-hits" onclick=\"showInfo()\">' + name + '</span>'
                            + '<br /> <span class="name-hits" style="color: cornflowerblue" onclick="logout()" >logout</span>';
}

function clearTbody(arg) {
    var tableList = document.getElementById(arg);
    var tbodys = tableList.getElementsByTagName("tbody");
    var len = tbodys.length;
    for (var i=0; i<len; ++i) {
        tableList.removeChild(tbodys[i]);
    }
}
function min(var1, var2) {
    if (var1 < var2) {
        return var1;
    }
    return var2;
}
function max(var1, var2) {
    if (var1 > var2) {
        return var1;
    }
    return var2;
}
//rank list page functions
function showRankList(data) {
    var allPages = data.allPages;
    var nowPage = data.nowPage;
    var stI = (nowPage - 1) * rankListPageSize + 1;
    var content = data.list;
    var len = content.length;
    var tbody = document.createElement("tbody");
    clearTbody("tableList");
    document.getElementById("tableList").appendChild(tbody);
    for (var i=0; i<len; ++i) {
        tbody.insertRow(i);
        var tl = tbody.rows[i];
        var user = content[i];
        if (i%2 == 1) {
            tl.className = "line-2";
        }
        tl.insertCell(0); tl.cells[0].innerHTML = String(i+stI);
        tl.insertCell(1); tl.cells[1].innerHTML = "<a href='user?userName=" + user.name + "'>" + user.name + "</a>";
        tl.insertCell(2); tl.cells[2].innerHTML = user.nick;
        tl.insertCell(3); tl.cells[3].innerHTML = user.school;
        tl.insertCell(4); tl.cells[4].innerHTML = user.solved;
        tl.insertCell(5); tl.cells[5].innerHTML = user.submit;
        var ratio = "0";
        if (user.submit != 0) {
            var tnum = user.solved / user.submit * 100;
            ratio = String(tnum.toFixed(2)) + "%";
        }
        tl.insertCell(6); tl.cells[6].innerHTML = ratio;
    }
    document.getElementById("pageInput").value = nowPage;
    document.getElementById("nowPage").innerHTML = nowPage;

    var t = "goPage(" + max(Number(nowPage)-1, 1) + ")";
    document.getElementById("pre").onclick = Function(t);
    t = "goPage(" + min(Number(nowPage)+1, allPages) + ")";
    document.getElementById("next").onclick = Function(t);
    t = "goPage(" + String(allPages) + ")";
    document.getElementById("end").onclick = Function(t); 
}
//rank list page end

//status page start
var myLan = ["GCC", "G++", "Java", "Pascal", "Python", "UNKNOWN"];
function getLan(arg) {
    return myLan[arg-1];
}
var myRes = [
    ["Accepted", "ac"],
    ["Memory Limit Exceeded", "err"],
    ["Time Limit Exceeded", "tl"],
    ["Runtime Error", "err"],
    ["Output Limit Exceeded", "err"],
    ["Dangerous Call", "err"],
    ["Compile Error", "ce"],
    ["Wrong Answer", "wa"],
    ["Presentation Error", "pe"],
    ["Waiting", ""]
]
function getRes(arg) {
    if (arg == null) {
        arg = 9;
    }
    return myRes[arg];
}
function showStatus(data) {
    var allPages = data.allPages;
    var nowPage = data.nowPage;
    var content = data.list;
    var len = content.length;
    var tbody = document.createElement("tbody");
    var localName = null;
    if (localStorage.getItem("name") != null) {
        localName = localStorage.getItem("name");
    }
    clearTbody("tableList");
    document.getElementById("tableList").appendChild(tbody);
    for(var i=0; i<len; ++i) {
        tbody.insertRow(i);
        var tl = tbody.rows[i];
        var myStatus = content[i];
        if (i%2 == 1) {
            tl.className = "line-2";
        }
        var solutionText = null;
        if (localName != null && localName == myStatus.userName) {
            solutionText = "<a href='javascript:void(0);' style='border-style: solid; border-width: thin' onclick='showCode(" +
                           myStatus.solutionId + ")'>" + 
                           String(myStatus.solutionId) + "</a>";
        }
        else {
            solutionText = String(myStatus.solutionId);
        }
        tl.insertCell(0); tl.cells[0].innerHTML = solutionText;
        tl.insertCell(1); tl.cells[1].innerHTML = "<a href='problem?problemId=" + myStatus.problemId + "'>" + myStatus.problemId + "</a>";
        tl.insertCell(2); tl.cells[2].innerHTML = "<a href='user?userName=" + myStatus.userName + "'>" + myStatus.userName + "</a>";
        tl.insertCell(3); tl.cells[3].innerHTML = getLan(myStatus.lang);
        var res = getRes(myStatus.state);
        tl.insertCell(4); tl.cells[4].innerHTML = res[0]; tl.cells[4].className = res[1];
        tl.insertCell(5);
        tl.insertCell(6);
        if (myStatus.state != null) {
            tl.cells[5].innerHTML = String(myStatus.maxMemory) + "KB";
            tl.cells[6].innerHTML = String(myStatus.maxTime) + "ms";
        }
        tl.insertCell(7); tl.cells[7].innerHTML = String(myStatus.codeLength) + "B";
        tl.insertCell(8); tl.cells[8].innerHTML = myStatus.submitTime;
    }
    document.getElementById("pageInput").value = nowPage;
    document.getElementById("nowPage").innerHTML = nowPage;

    var t = "goPage(" + max(Number(nowPage)-1, 1) + ")";
    document.getElementById("pre").onclick = Function(t);
    t = "goPage(" + min(Number(nowPage)+1, allPages) + ")";
    document.getElementById("next").onclick = Function(t);
    t = "goPage(" + String(allPages) + ")";
    document.getElementById("end").onclick = Function(t); 
}
//status page end

//contest list page start
var myContestType = ["ACM", "OI", "UNDEF", "CSP"];
function getContestType(arg) {
    return myContestType[arg];
}
function getPrivate(arg) {
    if (arg == false) {
        return "Public";
    }
    return "Private";
}
function showContestList(data) {
    var allPages = data.allPages;
    var nowPage = data.nowPage;
    var content = data.list;
    var len = content.length;
    var tbody = document.createElement("tbody");
    clearTbody("tableList");
    document.getElementById("tableList").appendChild(tbody);
    for (var i=0; i<len; ++i) {
        tbody.insertRow(i);
        var tl = tbody.rows[i];
        var contest = content[i];
        if (i%2 == 1) {
            tl.className = "line-2";
        }
        tl.insertCell(0); tl.cells[0].innerHTML = String(contest.contestId);
        tl.insertCell(1); tl.cells[1].innerHTML = "<a href='detailcontest/problem?contestId=" + contest.contestId + "'>" + contest.title + "</a>";
        tl.insertCell(2); tl.cells[2].innerHTML = contest.startTime;
        tl.insertCell(3); tl.cells[3].innerHTML = contest.duration;
        tl.insertCell(4); tl.cells[4].innerHTML = contest.frozenTime;
        tl.insertCell(5); tl.cells[5].innerHTML = contest.status;
        tl.insertCell(6); tl.cells[6].innerHTML = getPrivate(contest.private);
        tl.insertCell(7); tl.cells[7].innerHTML = getContestType(contest.contestType);
        tl.insertCell(8); tl.cells[8].innerHTML = contest.printer;
    }
    document.getElementById("pageInput").value = nowPage;
    document.getElementById("nowPage").innerHTML = nowPage;

    var t = "goPage(" + max(Number(nowPage)-1, 1) + ")";
    document.getElementById("pre").onclick = Function(t);
    t = "goPage(" + min(Number(nowPage)+1, allPages) + ")";
    document.getElementById("next").onclick = Function(t);
    t = "goPage(" + String(allPages) + ")";
    document.getElementById("end").onclick = Function(t); 
}
//contest list page end

//problem list page start
function getSovled(arg) {
    if (arg == "1") {
        return "√";
    }
    else if (arg == "0") {
        return "?";
    }
    return "";
}
function showProblemList(data) {
    var allPages = data.allPages;
    var nowPage = data.nowPage;
    var content = data.list;
    var len = content.length;
    var tbody = document.createElement("tbody");
    clearTbody("tableList");
    document.getElementById("tableList").appendChild(tbody);
    for (var i=0; i<len; ++i) {
        tbody.insertRow(i);
        var tl = tbody.rows[i];
        var problem = content[i];
        if (i%2 == 1) {
            tl.className = "line-2";
        }
        tl.insertCell(0); tl.cells[0].innerHTML = getSovled(problem.solved);
        tl.insertCell(1); tl.cells[1].innerHTML = String(problem.problemId);
        tl.insertCell(2); tl.cells[2].innerHTML = "<a href='problem?problemId=" + problem.problemId + "'>" + problem.title + "</a>";
        var t = problem.source;
        tl.insertCell(3); tl.cells[3].innerHTML = (t==null? "" : t);
        var ratio = "0";
        if (problem.submits != 0) {
            var tnum = problem.accepts / problem.submits * 100;
            ratio = String(tnum.toFixed(2)) + "%";
        }
        tl.insertCell(4); tl.cells[4].innerHTML = ratio + "(" + String(problem.accepts) + "/" + String(problem.submits) + ")";
    }

    document.getElementById("pageInput").value = nowPage;
    document.getElementsByClassName("nowPage")[0].innerHTML = nowPage;
    document.getElementsByClassName("nowPage")[1].innerHTML = nowPage;

    var t = "goPage(" + max(Number(nowPage)-1, 1) + ")";
    document.getElementsByClassName("pre")[0].onclick = Function(t);
    document.getElementsByClassName("pre")[1].onclick = Function(t);
    t = "goPage(" + min(Number(nowPage)+1, allPages) + ")";
    document.getElementsByClassName("next")[0].onclick = Function(t);
    document.getElementsByClassName("next")[1].onclick = Function(t);
    t = "goPage(" + String(allPages) + ")";
    document.getElementsByClassName("end")[0].onclick = Function(t); 
    document.getElementsByClassName("end")[1].onclick = Function(t); 
}
//problem list page end

//problem information page start
function loadProblem(docType) {
    var problemUrl = ojurl + "/common/problem/" + problemId + "." + docType;
    if (docType == "pdf") {
        document.getElementById("problemContent").href = problemUrl;
        $("a.media").media({
            width:  "100%",
            height: "700"
        });
    }
    else if (docType == "html") {
        document.getElementById("content").innerHTML 
        = '<iframe src="' + problemUrl + '" style="zoom: 50%" width="100%" height="1600"></iframe>';
    }
    else if (docType == "md") {
        $.get({
            url: problemUrl,
            success: function(md) {
                editormd.markdownToHTML("content", {
                    markdown        : md ,
                    htmlDecode      : "style,script,iframe",
                    tocm            : true,
                    emoji           : true,
                    taskList        : true,
                    tex             : true,  // 默认不解析
                });
            }
        });
    }
    else {
        alert("error!");
    }
}

function showProblemInfo(data) {
    document.getElementById("pid").innerHTML = data.problemId;
    if (data.isSpj == true) {
        document.getElementById("spj").className = "wa";
        document.getElementById("spj").innerHTML = "Yes";
    }
    else {
        document.getElementById("spj").className = "ac";
        document.getElementById("spj").innerHTML = "No";
    }
    document.getElementById("tl").innerHTML = String(data.timeLimit * 1000) + "MS";
    document.getElementById("stl").innerHTML = String(data.timeLimitSpc*1000) + "MS";
    document.getElementById("ml").innerHTML = String(data.memoryLimit) + "M";
    document.getElementById("submits").innerHTML = data.submits;
    document.getElementById("accepted").innerHTML = data.accepts;
    document.getElementById("author").innerHTML = data.author;
    document.getElementById("source").innerHTML = data.source;
    document.getElementById("title").innerHTML = data.title;
    loadProblem(data.docType);
}
//problem information page end